<template>
  <vol-box
    :lazy="true"
    v-model="model"
    title="选择客户"
    :height="400"
    :width="1200"
    :padding="5"
  >
    <div>
      <client ref="client"></client>
    </div>
    <template #footer>
      <div>
        <el-button type="primary" size="small" @click="onSelect"
          >确认</el-button
        >
      </div>
    </template>
  </vol-box>
  <vol-box
    :lazy="true"
    v-model="detailModel"
    title="选择商品"
    :height="400"
    :width="1200"
    :padding="5"
    :onModelClose="onModelClose"
  >
    <div>
      <goodsInfo ref="goodsInfo"></goodsInfo>
    </div>
    <template #footer>
      <div>
        <el-button type="primary" size="small" @click="detailOnSelect"
          >确认</el-button
        >
      </div>
    </template>
  </vol-box>
  <vol-box
    :lazy="true"
    v-model="detailWarehouseModel"
    title="选择仓库"
    :height="400"
    :width="1200"
    :padding="5"
  >
    <div>
      <warehouse ref="warehouse"></warehouse>
    </div>
    <template #footer>
      <div>
        <el-button type="primary" size="small" @click="detailWarehouseOnSelect"
          >确认</el-button
        >
      </div>
    </template>
  </vol-box>
</template>
<script>
import VolBox from "@/components/basic/VolBox.vue";
import client from "@/views/customerinfo/q_client/q_client.vue";
import goodsInfo from "@/views/basicinfo/goods_info/q_goods_info.vue";
import warehouse from "@/views/inventoryinfo/warehouse/q_warehouse.vue";
//这里使用的vue2语法，也可以写成vue3语法
export default {
  components: {
    "vol-box": VolBox,
    client,
    goodsInfo,
    warehouse,
  },
  data() {
    return {
      model: false,
      detailModel: false,
      detailWarehouseModel: false,
      WHSE_Id: "",
      // purchaseApplicationModel: false,
    };
  },
  methods: {
    async onModelClose() {
      this.type = null;
      this.goodsFittingsDetail = null;
      this.$refs.goodsInfo.searchFormFields.Item_sub = null;
      this.$refs.goodsInfo.searchFormFields.Item_name = null;
      this.$refs.goodsInfo.searchFormFields.Item_clsno = null;
      this.$refs.goodsInfo.searchFormFields.Item_brandname = null;
      this.$refs.goodsInfo.searchFormFields.Display_flag = null;
      this.$refs.goodsInfo.searchFormFields.Supplier = null;
      // this.$refs.goodsInfo.searchFormFields.AuditStatus = "1";
      this.$refs.goodsInfo.searchFormFields.Item_subno = null;
      this.$refs.goodsInfo.searchFormFields.Cost_accounting = null;
      // await this.$refs.goodsInfo.$refs.grid.search();
      this.$refs.goodsInfo.$refs.grid.$refs.table.reset();
      let startTime = this.base.getOneWeekAgoDate();
          let endTime = this.base.getDate(false) + " 23:59:59";
          this.$refs.goodsInfo.searchFormFields.CreateDate = [
            startTime,
            endTime,
          ];

    },
    open() {
      this.model = true;
      let setIntervalTiem = setInterval(() => {
        if (this.$refs.goodsInfo) {
          clearInterval(setIntervalTiem);
          // this.$refs.goodsInfo.$refs.grid.search();
        }
      }, 100);
    },
    detailOpen(value) {
      if (this.$route.path == "/q_stock_in") {
        this.WHSE_Id = value;
      } else {
        this.type = value;
      }
      this.detailModel = true;
      let setIntervalTiem = setInterval(() => {
        if (this.$refs.goodsInfo) {
          clearInterval(setIntervalTiem);
          // this.$refs.goodsInfo.searchFormFields.AuditStatus = "1";
          this.$refs.goodsInfo.searchFormFields.Cost_accounting = null;
          this.$refs.goodsInfo.searchFormFields.Item_sub = null;
          this.$refs.goodsInfo.searchFormFields.Item_name = null;
          this.$refs.goodsInfo.searchFormFields.Item_clsno = null;
          this.$refs.goodsInfo.searchFormFields.Item_brandname = null;
          this.$refs.goodsInfo.searchFormFields.Item_subno = null;
          this.$refs.goodsInfo.searchFormFields.Display_flag = null;
          this.$refs.goodsInfo.searchFormFields.Supplier = null;
          let startTime = this.base.getOneWeekAgoDate();
          let endTime = this.base.getDate(false) + " 23:59:59";
          this.$refs.goodsInfo.searchFormFields.CreateDate = [
            startTime,
            endTime,
          ];

          // this.$refs.goodsInfo.$refs.grid.search()
        }
      }, 100);
    },
    goodsFittingsOpen(value) {
      this.type = value;
      this.detailModel = true;
      let setIntervalTiem = setInterval(() => {
        if (this.$refs.goodsInfo) {
          clearInterval(setIntervalTiem);
          this.$refs.goodsInfo.searchFormFields.Item_brandname = "1";
          let startTime = this.base.getOneWeekAgoDate();
          let endTime = this.base.getDate(false) + " 23:59:59";
          this.$refs.goodsInfo.searchFormFields.CreateDate = [
            startTime,
            endTime,
          ];
          // this.$refs.goodsInfo.$refs.grid.search();
        }
      }, 100);
    },
    goodsFittingsDetailOpen(value, Detail) {
      this.type = value;
      this.goodsFittingsDetail = Detail;
      this.detailModel = true;
    },
    detailWarehouseOpen() {
      this.detailWarehouseModel = true;
      let setIntervalTiem = setInterval(() => {
        if (this.$refs.goodsInfo) {
          clearInterval(setIntervalTiem);
          this.$refs.warehouse.$refs.grid.search();
        }
      }, 100);
    },

    onSelect() {
      let rowObj = this.$refs.client.$refs.grid.getSelectRows();
      if (!rowObj.length) {
        return this.$message.error("请选择客户");
      }
      this.$emit("parentCall", ($parent) => {
        //这里还要设置客户ID,避免名称改动查找不到目标
        if (this.$route.path == "/q_goodsIn_class") {
          $parent.editFormFields.GoodsIn_client = rowObj[0].Client_name;
        } else if (this.$route.path == "/q_goodsOut_class") {
          $parent.editFormFields.GoodsOut_client = rowObj[0].Client_name;
        }
      });
      return (this.model = false);
    },
    async detailOnSelect() {
      let rowObj = this.$refs.goodsInfo.$refs.grid.getSelectRows();
      if (!rowObj.length) return this.base.ElMessageFn("请选择商品", "warning");
      // 剔除非审核通过
      let sumLength = rowObj.length;
      rowObj = rowObj.filter((item) => item.AuditStatus == 1);
      console.log("rowObj.length", rowObj.length);
      if (rowObj.length == 0) {
        this.$message.warning(`请选择审核通过商品`);
        return;
      }
      if (rowObj.length != sumLength) {
        this.$message.warning(`已剔除非审核通过商品`);
      }

      if (this.$route.path == "/q_goods_fittings") {
        if (this.goodsFittingsDetail == "明细表") {
          this.$emit("parentCall", ($parent) => {
            let parentList = $parent.$refs.detail.rowData;
            let set = new Set(parentList.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此明细单`);
            }
            let newRowObj = rowObj.map((item) => {
              return {
                Goods_sub: item.Item_sub,
                Goods_name: item.Item_name,
                Goods_size: item.Item_size,
                Item_clsno: item.Item_clsno,
                Item_brand: item.Item_brand,
                Item_subno: item.Item_subno,
                Sale_price: item.Sale_price,
              };
            });
            $parent.$refs.detail.rowData.unshift(...newRowObj);
            this.onModelClose();
            return (this.detailModel = false);
          });
        } else {
          if (rowObj.length > 1) {
            this.base.ElMessageFn("请选择一个商品");
            return;
          }

          try {
            let Item_brandnameSome = rowObj.some(
              (item) => item.Item_brandname != 1
            );
            if (Item_brandnameSome) {
              this.base.ElMessageFn("请选择自研商品");
              return;
            }
            this.$emit("parentCall", ($parent) => {
              $parent.editFormFields.Goods_sub = rowObj[0].Item_sub;
              $parent.editFormFields.Goods_name = rowObj[0].Item_name;
            });
            this.onModelClose();
            return (this.detailModel = false);
          } catch (error) {
            console.error(error);
          }
        }
      }
      if (this.$route.path == "/q_goods_inventory") {
        this.$emit("parentCall", ($parent) => {
          $parent.searchFormFields.goods_code = rowObj[0].Item_sub;
          this.onModelClose();
          return (this.detailModel = false);
        });
      }
      if (
        // this.$route.path == "/q_other_in_out" ||
        this.$route.path == "/q_overflow_voucher"
      ) {
        // 剔除非审核通过
        let sumLength = rowObj.length;
        rowObj = rowObj.filter((item) => item.AuditStatus == 1);
        if (rowObj.length != sumLength) {
          this.$message.warning(`已剔除非审核通过商品`);
        }
        this.$emit("parentCall", ($parent) => {
          let parentList = $parent.$refs.detail.rowData;
          let set = new Set(parentList.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
          let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
          let goodsNamesSet = new Set(
            commonObjects.map((item) => item.Item_sub)
          ); //相同商品的编码
          if (commonObjects.length) {
            rowObj = rowObj.filter((item) => !goodsNamesSet.has(item.Item_sub)); //在选中数据中剔除明细表已包含的行数据
            let str = "";
            commonObjects.forEach((r) => {
              if (str == "") str += r.Item_name;
              else str = str + "," + r.Item_name;
            });
            this.$message.warning(`商品${str}已存在此明细单`);
          }
          let newRowObj = rowObj.map((item) => {
            let obj = {
              Goods_sub: item.Item_sub,
              Goods_name: item.Item_name,
              Goods_size: item.Item_size,
              Cost_accounting: item.Cost_accounting,
              // Tax_rate: item.Tax_rate,
              // Type: this.type,
              CostPrice: 0,//报溢价格都是0，成本价
              Tax_exclusive: 0,//报溢价格都是0，无税成本
              // Overflow_price: 0,//报溢价格都是0，报溢单价
              // Tax_exclusive_overflow_price: 0,//报溢价格都是0，无税报溢单价
              // Overflow_price_total_price: 0,//报溢价格都是0，报溢金额
              // Tax_exclusive_overflow_price_total_price: 0,//报溢价格都是0，无税报溢金额
            };
            if (this.type == "赠品") {
              obj.Goods_price = 0;
            }
            return obj;
          });
          this.$emit("parentCall", ($parent) => {
            $parent.$refs.detail.rowData.unshift(...newRowObj);
            if (newRowObj.length && this.$route.path == "/q_overflow_voucher") {
              $parent.WHSE_IdDisableFn();
            }
          });
        });
        this.onModelClose();
        return (this.detailModel = false);
      }
      if (this.$route.path == "/q_purchase_application") {
        this.$emit("parentCall", ($parent) => {
          try {
            // 剔除非审核通过
            let sumLength = rowObj.length;
            rowObj = rowObj.filter((item) => item.AuditStatus == 1);
            if (rowObj.length != sumLength) {
              this.$message.warning(`已剔除非审核通过商品`);
            }
            //处理明细表已含有相同数据
            let parentList = $parent.$refs.detail.rowData;
            let set = new Set(parentList.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此采购申请单`);
            }
            let arr = rowObj.map((item) => {
              return {
                Goods_sub: item.Item_sub,
                Goods_name: item.Item_name,
                Goods_size: item.Item_size,
                Tax_rate: item.Tax_rate,
                Purchase_state: 0,
              };
            });
            $parent.$refs.detail.rowData.unshift(...arr);
          } catch (e) {
            console.log(e);
          }
        });
        this.onModelClose();
        return (this.detailModel = false);
      }
      if (this.$route.path == "/q_warehouse_location") {
        this.$emit("parentCall", ($parent) => {
          try {
            // 剔除非审核通过
            let sumLength = rowObj.length;
            rowObj = rowObj.filter((item) => item.AuditStatus == 1);
            if (rowObj.length != sumLength) {
              this.$message.warning(`已剔除非审核通过商品`);
            }
            //处理明细表已含有相同数据
            let parentList = $parent.$refs.detail.rowData;
            let set = new Set(parentList.map((item) => item.Item_sub)); //得到由明细表goods_sub组成的数组
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此库位`);
            }
            let newRowObj = rowObj.map((item) => {
              return {
                Item_sub: item.Item_sub,
                Item_name: item.Item_name,
              };
            });
            $parent.$refs.detail.rowData.unshift(...newRowObj);
          } catch (error) {
            console.error(error);
          }
          this.onModelClose();
          return (this.detailModel = false);
        });
      } else if (this.$route.path == "/q_goodsOut_class") {
      }
      if (this.$route.path == "/q_stock_in") {
        this.$emit("parentCall", ($parent) => {
          try {
            // 剔除非审核通过
            let sumLength = rowObj.length;
            rowObj = rowObj.filter((item) => item.AuditStatus == 1);
            if (rowObj.length != sumLength) {
              this.$message.warning(`已剔除非审核通过商品`);
            }
            let arr = [];
            //处理明细表已含有相同数据
            let parentList = $parent.$refs.detail.rowData;
            let vSub = parentList.filter((item) => item.Voucher_sub); //采购单商品
            let Sub = parentList.filter((item) => item.Voucher_sub == null); //商品信息商品
            let set = new Set(Sub.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此入库单`);
            }
            arr = rowObj.map((item) => {
              return {
                Goods_sub: item.Item_sub,
                Goods_name: item.Item_name,
                Goods_size: item.Item_size,
                Cost_price: item.Price_in,
                Tax_rate: item.Tax_rate,
                // Cost_accounting: item.Cost_accounting,
                Tax_exclusive: this.base.roundToFourDecimals(
                  item.Price_in / (1 + +item.Tax_rate)
                ),
                Production_state: 1,
              };
            });
            arr = this.base.getPushDatileWHSEName(
              arr,
              "Goods_sub",
              this.WHSE_Id
            );
            $parent.$refs.detail.rowData.unshift(...arr);
          } catch (error) {
            console.log(error);
          }
        });
        this.onModelClose();
        return (this.detailModel = false);
      }
      if (
        this.$route.path == "/q_goodsIn_class" ||
        this.$route.path == "/q_sales_contract"
      ) {
        // 剔除非审核通过
        let sumLength = rowObj.length;
        rowObj = rowObj.filter((item) => item.AuditStatus == 1);
        if (rowObj.length != sumLength) {
          this.$message.warning(`已剔除非审核通过商品`);
        }
        this.$emit("parentCall", async ($parent) => {
          try {
            let parentList = $parent.$refs.detail.rowData;
            let set;
            if (this.$route.path == "/q_goodsIn_class") {
              set = new Set(parentList.map((item) => item.GoodsInList_sub)); //得到由明细表goods_sub组成的数组
            } else if (this.$route.path == "/q_sales_contract") {
              set = new Set(parentList.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
            }
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此明细单`);
            }
            let newRowObj = rowObj.map((item) => {
              if (this.$route.path == "/q_goodsIn_class") {
                return {
                  GoodsInList_sub: item.Item_sub,
                  GoodsInList_name: item.Item_name,
                  GoodsInList_size: item.Item_size,
                  GoodsInList_price: item.Sale_price,
                };
              }

              if (this.$route.path == "/q_sales_contract") {
                return {
                  Goods_sub: item.Item_sub,
                  Goods_name: item.Item_name,
                  Goods_num: 1,
                  Goods_size: item.Item_size,
                  Total_price: item.Sale_price,
                  Goods_price: item.Sale_price,
                  Logistics_status: 0,
                  Install_status: 0,
                  CostPrice: item.Price_in,
                };
              }
            });
            if (this.$route.path == "/q_goodsIn_class") {
              this.getDatileSelectFn($parent, "GoodsInList_sub");
            }
            $parent.$refs.detail.rowData.unshift(...newRowObj);
          } catch (e) {
            console.log(e);
          }
        });
        this.onModelClose();
        return (this.detailModel = false);
      }
      if (this.$route.path == "/q_fittings_delivery") {
        this.$emit("parentCall", ($parent) => {
          try {
            // 剔除非审核通过
            let sumLength = rowObj.length;
            rowObj = rowObj.filter((item) => item.AuditStatus == 1);
            if (rowObj.length != sumLength) {
              this.$message.warning(`已剔除非审核通过商品`);
            }
            let arr = [];
            //处理明细表已含有相同数据
            let parentList = $parent.$refs.detail.rowData;
            // let vSub = parentList.filter((item) => item.Voucher_sub); //采购单商品
            let Sub = parentList.filter((item) => item.Voucher_sub == null); //商品信息商品
            let set = new Set(Sub.map((item) => item.Goods_sub)); //得到由明细表goods_sub组成的数组
            let commonObjects = rowObj.filter((item) => set.has(item.Item_sub)); //得到明细表中已包含的选中行
            let goodsNamesSet = new Set(
              commonObjects.map((item) => item.Item_sub)
            ); //相同商品的编码
            if (commonObjects.length) {
              rowObj = rowObj.filter(
                (item) => !goodsNamesSet.has(item.Item_sub)
              ); //在选中数据中剔除明细表已包含的行数据
              let str = "";
              commonObjects.forEach((r) => {
                if (str == "") str += r.Item_name;
                else str = str + "," + r.Item_name;
              });
              this.$message.warning(`商品${str}已存在此配件发货单`);
            }
            arr = rowObj.map((item) => {
              return {
                Goods_sub: item.Item_sub,
                Goods_name: item.Item_name,
                Goods_size: item.Item_size,
                Cost_price: item.Price_in,
                Goods_num: 1,
              };
            });
            $parent.$refs.detail.rowData.unshift(...arr);
          } catch (error) {
            console.log(error);
          }
        });
        this.onModelClose();
        return (this.detailModel = false);
      }
    },
    detailWarehouseOnSelect() {
      let rowObj = this.$refs.warehouse.$refs.grid.getSelectRows();
      if (!rowObj.length) {
        return this.$message.error("请选择数据");
      }
      this.$emit("parentCall", ($parent) => {
        let tableData = $parent.$refs.table.rowData;
        if (
          tableData.findIndex((item) => item.WHSE_no == rowObj[0].WHSE_no) != -1
        ) {
          return this.$message.error("列表中已存在当前库位");
        }
        $parent.editFormFields.WHSE_name = rowObj[0].WHSE_name;
        $parent.editFormFields.WHSE_no = rowObj[0].WHSE_no;
        return (this.detailWarehouseModel = false);
      });
    },

    //明细表库位下拉框
    async getDatileSelectFn($parent, sub) {
      try {
        console.log(99);

        let rows = $parent.$refs.detail.rowData;
        await rows.forEach((row) => {
          $parent.$refs.detail.columns.forEach((item) => {
            if (item.field == "WHSE_name") {
              let selectUrl = `api/q_warehouse_locationList/getgoodslocation?bm=${row[sub]}`;
              item.bind.data.forEach((d) => {
                d.hidden = true;
              });
              this.http.post(selectUrl, {}, "").then((reslut) => {
                item.bind.data.forEach((d) => {
                  d.hidden = true;
                });
                item.bind.data.forEach((d) => {
                  reslut.forEach((j) => {
                    if (d.key == j.WHSE_no) {
                      d.hidden = false;
                    }
                  });
                });
                row.WHSE_name = item.bind.data.filter(
                  (x) => x.hidden == false
                )[0].key;
              });
            }
          });
        });
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>